<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <!-- immediate-check -->
    <comment-item
      @reply-click="$emit('reply-click', $event)"
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
    ></comment-item>
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment.js'
import CommentItem from './comment-item.vue'
import { on } from '@/utils/eventBus.js'
export default {
  mounted () {
    on('onpost-success', (comment) => {
      this.list.unshift(comment)
    })
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator (val) {
        return ['a', 'c'].includes(val)
      },
      default: 'a'
    }
  },
  components: { CommentItem },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 20
    }
  },
  methods: {
    async  onLoad () {
      // 1. 请求获取数据
      const { data: { data }, data: { data: { results, last_id: offset } } } = await getComments({
        type: this.type, //  评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
        source: this.source, // 源id，文章id或评论id
        offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
        limit: this.limit// 获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
      })
      this.$emit('on-load', data)
      this.list.push(...results)// 2. 将数据添加到列表中
      Object.assign(this, {

        loading: false, // 3. 将 loading 设置为 false
        finished: results.length === 0, // 4. 判断是否还有数据

        offset // 有就更新获取下一页的数据页码
      })
      // 没有就将 finished 设置结束
    }
  },
  created () {
    this.loading = true
    this.onLoad()
  }
}
</script>

<style lang="less" scoped>
</style>
